<?php
namespace app\admin\model;
use think\Image;
use think\Model;

class Goods extends Model
{
    protected $field = true;
    protected static function init()
    {
    Goods::afterInsert(function ($goods) {
        $goodsId=$goods->id;
        $data=input('post.');
        db('goodsattr')->insert(['goods_id'=>$goodsId,'manufactor'=>$data['manufactor'],'qualityday'=>$data['qualityday'],'weight'=>$data['weight'],'unit'=>$data['unit'],'flavor'=>$data['flavor']]);



        if ($goods->hasImgs($_FILES['goods_images']['tmp_name'])) {
            $files = request()->file('goods_images');
            foreach ($files as $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move('../public/static/admin/uploads/');
                if ($info) {
                    // 输出 42a79759f284b767dfcb2a0197904287.jpg
                    $photoName = $info->getFilename();
                    $ogphoto = date("Ymd") . '/' . $photoName;
                    $bigphoto = date("Ymd") . '/' . 'big_' . $photoName;
                    $midphoto = date("Ymd") . '/' . 'mid_' . $photoName;
                    $smphoto = date("Ymd") . '/' . 'sm_' . $photoName;
                    $image = Image::open('../public/static/admin/uploads/' . $ogphoto);
                    $image->thumb(430, 500)->save('../public/static/admin/uploads/' . $bigphoto);
                    $image->thumb(430, 430)->save('../public/static/admin/uploads/' . $midphoto);
                    $image->thumb(40, 40)->save('../public/static/admin/uploads/' . $smphoto);
                    db('photo')->insert(['goods_id' => $goodsId, 'big_photo' => $bigphoto,'og_photo'=>$ogphoto, 'mid_photo' => $midphoto, 'sm_photo' => $smphoto]);
                    unset($info);
                } else {
                    // 上传失败获取错误信息
                    echo $file->getError();
                }
                unset($info);
            }
        }
    });
        Goods::afterdelete(function (){
            $goodsid=input('get.id');
            //dump($id);
            db('goodsattr')->where('goods_id',$goodsid)->delete();
            db('photo')->where('goods_id',$goodsid)->delete();
        });
    }
    public function upload($imgName)
    {
        $file = request()->file($imgName);
        if ($file) {
            $info = $file->move('../public/static/admin/uploads/');
            if ($info) {
                return [$info->getFilename(),$info];
            } else {
                echo $file->getError();
            }
        }
        unset($info);
    }

    private function hasImgs($tmpArr){
        foreach ($tmpArr as $k => $v) {
            if($v){
                return true;
            }
        }
        return false;
    }
}